/**
 * Copyright (C), 2015-2020, XXX有限公司
 * <p>
 * FileName: MyDecisionManager
 * <p>
 * Author:   Brill
 * <p>
 * Date:     2020/2/29/029 14:46
 * <p>
 * Description: 查看用户是否具有可以访问的角色
 * <p>
 * History:
 *
 * <author>          <time>          <version>          <desc>
 * <p>
 * 作者姓名           修改时间           版本号              描述
 */


package cn.yuhh.config;


import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 〈一句话功能简述〉<br> 
 * 〈查看用户是否具有可以访问的角色〉
 *
 * @author Brill

 * @create 2020/2/29/029

 * @since 1.0.0

 */
@Component
public class MyDecisionManager implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //这里的collection内的数据,就是从myFilter内返回的数据,就是请求地址需要的用户角色
        for (ConfigAttribute configAttribute : collection) {
            String needRole = configAttribute.getAttribute();

            if ("ROLE_LOGIN".equals(needRole)) {
                //如果现在的用户没有登录
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("你没有登录!请先登录");
                } else {
                    return;
                }
            }

            //authentication内存放的是已登录用户的信息
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }

        throw new AccessDeniedException("权限不足,请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
